//
//  NewView.m
//  仿真开发
//
//  Created by Cloud on 2017/3/25.
//  Copyright © 2017年 B.HOPE. All rights reserved.
//

#import "NewView.h"
#import <Masonry.h>

@interface NewView ()<UIScrollViewDelegate>

@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, weak) UIPageControl *pageControl;

@end

@implementation NewView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        //添加srollView
        [self makeScrollView];
        
        //创建分页指示器
        UIPageControl *page = [[UIPageControl alloc] init];
        _pageControl = page;
        
        [self addSubview:page];
        
        page.currentPage = 0;
        
        page.pageIndicatorTintColor = [UIColor lightGrayColor];
        
        page.currentPageIndicatorTintColor = [UIColor blackColor];
        
        [page mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(-20);
            make.centerX.equalTo(self.mas_centerX).offset(0);
        }];
        page.enabled = NO;
    }
    return self;
}

// 创建scrollView
- (void)makeScrollView
{
    //创建scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    
    _scrollView = scrollView;
    
    [self addSubview:scrollView];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).offset(0);
    }];
    
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    _scrollView.delegate = self;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.tag == _imageNames.count) {
        [self removeFromSuperview];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width + 0.49999;
    
    _pageControl.currentPage = page;
    
    _pageControl.hidden = (_imageNames.count == page);
    
    scrollView.tag = page;
}

- (void)setImageNames:(NSArray *)imageNames
{
    _imageNames = imageNames;
    
    CGFloat scrollViewW = self.bounds.size.width;
    
    CGFloat scrollViewH = self.bounds.size.height;
    
    for (NSInteger i = 0; i < imageNames.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageNames[i] ofType:@"jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        imageView.image = image;
        imageView.frame = CGRectMake(scrollViewW * i, 0, scrollViewW, scrollViewH);
        [_scrollView addSubview:imageView];
        _scrollView.contentSize = CGSizeMake((imageNames.count + 1) * scrollViewW, 0);
        _pageControl.numberOfPages = imageNames.count;
    }
}

@end
